package com.bc.mcode.config;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements  TransactionManagementConfigurer {

    @Autowired
    DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {

        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.bc.mcode.model");

        SqlInterceptor sqlInterceptor = new SqlInterceptor();
        sqlInterceptor.setSqlType("mysql");
        //添加插件
        bean.setPlugins(new Interceptor[]{sqlInterceptor});
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] listOne = null;
            Resource mapping = resolver.getResource("classpath:mapping");
            if(mapping.exists()){
                listOne = resolver.getResources("classpath:mapping/*.xml");
            }else{
                listOne = new Resource[]{};
            }
            Resource[] listTwo = resolver.getResources("classpath*:com/bc/mcode/db/*.xml");
            int i = listOne.length + listTwo.length;
            int k = listOne.length;
            Resource[] list = new Resource[i];
            for (int j = 0; j < listOne.length; j++) {
                list[j] = listOne[j];
            }
            for(int j =0; j<listTwo.length; j++){
                list[k+j] = listTwo[j];
            }
            bean.setMapperLocations(list);
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }


}
